package com.inibb.app.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class BaseDao{
	
	private JdbcTemplate simpleJdbcTemplate;
	@Autowired
	private DataSource dataSource;
	public void setDataSource(DataSource ds){
		this.dataSource = ds;
	}

	public JdbcTemplate getSimpleJdbcTemplate() {
		if (simpleJdbcTemplate == null)
			simpleJdbcTemplate = new JdbcTemplate(dataSource);
		return simpleJdbcTemplate;
	}
	
	public String createAlterDrop(String sql) throws Exception {
		try{
		this.getSimpleJdbcTemplate().execute(sql);
		}catch(Exception e){
			throw e;
		}
		return "";
	}

	public String insertDeleteUpdate(String sql) throws Exception {
		sql = sql.trim();
		try{
		int rows=this.getSimpleJdbcTemplate().update(sql);
		return rows+" rows affected";
		}catch(Exception e){
			throw e;
		}
	}

	public List<List<String>> select(String sql) throws Exception {
		sql = sql.trim();
		List<Map<String, Object>> list=null;
		List<List<String>> results=new ArrayList<List<String>>();
		try{
		list = this.getSimpleJdbcTemplate().queryForList(sql);
		}catch(Exception e){
			throw e;
		}
		
		for(Object o:list){
			Map<String, Object> m = (Map)o;
			List<String> oneLine=new ArrayList<String>();
			Iterator it=m.values().iterator();
			while(it.hasNext()){
				Object obj = it.next();
				if(obj==null)
					oneLine.add(null);
				else
					oneLine.add(StringUtils.trim(obj.toString()));
			}
			results.add(oneLine);
		}
		return results;
	}
}
